import { getShopList, editShop, getShopDetail, reviewShop, upload } from '@/api/getData'
import { Message } from 'iview'

const state = {
  list: [],
  query: {
    total: 0,
    size: 10,
    page: 1,
    status: 1
  }
}

const mutations = {
  SET_LIST (state, data) {
    state.list = data
  },
  SET_QUERY (state, data) {
    const { total, page } = data
    state.query = Object.assign(state.query, {
      total, page
    })
  }
}

const actions = {
  _getShopList ({ commit }, params) {
    const { pageSize, page } = state.query
    return new Promise((resolve, reject) => {
      const data = { ...params, pageSize, page }
      getShopList(data).then(res => {
        const { error, payload } = res
        if (error === 200) {
          const { list, total, page } = payload
          commit('SET_LIST', list)
          commit('SET_QUERY', { total, page })
        } else {
          commit('SET_LIST', [])
          commit('SET_QUERY', { total: 0, page: 1, pageSize: 10 })
        }
      })
    })
  },
  _editShop ({ dispatch, state }, params) {
    return new Promise((resolve, reject) => {
      editShop(params).then(res => {
        const { error, message, payload } = res
        if (error === 200) {
          dispatch('_getShopList', state.query)
          resolve(payload)
        } else {
          Message.warning(message)
        }
      })
    })
  },
  // eslint-disable-next-line no-empty-pattern
  _getDetail ({}, id) {
    return new Promise((resolve, reject) => {
      getShopDetail(id).then(res => {
        const { error, payload, message } = res
        if (error === 200) {
          resolve(payload)
        } else {
          reject(message)
        }
      })
    })
  },
  // eslint-disable-next-line no-empty-pattern
  _reviewShop ({}, params) {
    return new Promise((resolve, reject) => {
      reviewShop(params).then(res => {
        const { error, message, payload } = res
        if (error === 200) {
          resolve(payload)
        } else {
          reject(message)
        }
      })
    })
  },
  // 上传文件
  _toUpload ({}, file) {
    return new Promise((resolve, reject) => {
      upload(file)
        .then(res => {
          const { error, message } = res
          if (error === 200) {
            resolve(message)
          } else {
            resolve(message)
          }
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
